import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useContext } from 'react';
import { Button, Modal, Input, Table, Space, Form, Pagination, Select, Radio, Image, Upload, Divider, DatePickerProps, TreeSelect, Switch } from 'antd';
import { FontSizeOutlined, PayCircleOutlined, BankOutlined, DesktopOutlined, ExclamationCircleOutlined, FileZipOutlined } from '@ant-design/icons';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';
import { commonErrorMsg, deepCopy, getChangeEventValue, isEmpty, toastShort } from './../utils';
import { MapTopic } from '../typings';
import SmartMapProvider from '../provider/SmartMapProvider';

interface Props {
    onFinish?: Function
}

const UploadShpFileModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }))

    const {
        tdt_map_token,
        mapbox_token,
        mapMountingRootId,
        uploadActionUrl,
        pageParamsTag,
        defaultMapLayerPid,
        addMapLayerPromiseFunc,
        editMapLayerPromiseFunc,
        deleteMapLayerPromiseFunc,
        queryMapLayerPromiseFunc,
        layerManageDrawerOpen,
        setLayerManageDrawerOpen
    } = useContext(SmartMapProvider);

    const { Dragger } = Upload;
    const { TextArea } = Input;

    const {
        onFinish
    } = props;

    const [submitLoading, setSubmitLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm<{ topicName?: string }>();
    const [uploadProgress, setUploadProgress] = useState<number>(0);
    const [formData, setFormData] = useState<MapTopic>({});
    const [shpFileName, setShpFileName] = useState('');
    const [layerDefaultColor, setLayerDefaultColor] = useState('');
    const [defaultFormData] = useState<MapTopic>({
        styleConfig: "{\"themeColor\":\"#ff0000\"}",
        //@ts-ignore
        layerColor: '#ff0000',
        layerType: null,
        name: '',
    });

    const [mapToicLoading, setMapToicLoading] = useState(false);
    const [mapTopicSelectOptions, setMapTopicSelectOptions] = useState([]);

    const handleConfirm = async () => { 
        try {
            const values = await form.validateFields();
            setSubmitLoading(true);
            let params: MapTopic = formData;
            console.log("params--->", params);
            let requestMethod = addMapLayerPromiseFunc;
            if (formData.id) {
                requestMethod = editMapLayerPromiseFunc;
            }
            requestMethod(params)
                .then(res => {
                    console.log("res", res)
                    onFinish && onFinish();
                    setIsModalOpen(false);
                    setSubmitLoading(false)
                })
                .catch(err => {
                    toastShort('error', commonErrorMsg)
                })
        } catch (e) {

        }
    };

    const openModal = (rowData: MapTopic) => {
        const { keys, values } = Object;
        if (rowData) {
            let _formData: MapTopic = deepCopy(rowData);
            if (rowData.styleConfig) {
                _formData.layerColor = JSON.parse(rowData.styleConfig).themeColor;
            }
            const keyList = keys(_formData);
            const valueList = values(_formData)
            keyList.forEach((key, index) => {
                form.setFieldValue(key, valueList[index])
            })
            setFormData(_formData);
        } else {
            let _formData = deepCopy(defaultFormData);
            const keyList = keys(_formData);
            const valueList = values(_formData)
            keyList.forEach((key, index) => {
                form.setFieldValue(key, valueList[index])
            })
            setFormData(_formData);
        }
        setIsModalOpen(true);
        queryMapTopic();
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const handleSetFormData = (target: string, value: any) => {
        let _formData = formData;
        //@ts-ignore
        _formData[target] = value;
        setFormData(deepCopy(_formData));
    };

    const onLayerTypeChange = (e: string) => {
        handleSetFormData('layerType', e);
    }

    const onLayerColorChange = (e: any) => {
        try {
            console.log("onLayerColorChange-->", e)
            const { r, g, b, a } = e.metaColor;
            const rgba = `rgba(${r.toFixed(0)},${g.toFixed(0)},${b.toFixed(0)},${Number(a.toFixed(1))})`;
            console.log("rgba--->", rgba)
            let { styleConfig } = formData;
            let styleConfigInstance = {};
            if (!isEmpty(styleConfig)) {
                styleConfigInstance = JSON.parse(styleConfig);
            }
            //@ts-ignore
            styleConfigInstance.themeColor = rgba;
            handleSetFormData('styleConfig', JSON.stringify(styleConfigInstance));
        } catch (e) {
            toastShort('error', commonErrorMsg)
        }
    }

    const onMapTopicIdChange = (e: string) => {
        handleSetFormData('pid', e);
    }

    const beforeUploadAPK = async (file) => {
        console.log("file---->", file)
    };

    const onFileChange = (e) => {
        try {
            console.log("onFileChange--->", e)
            const fileName = e.file.name.split('.')[0];
            console.log("fileName--->", fileName)
            // return false;
            if (e.fileList.length == 0) {
                //删除了文件
                console.log("文件是空的")
            } else {
                //选择了文件
                if (e.event && e.event.percent) {
                    setUploadProgress(e.event.percent);
                } else if (e.file && e.file.response) {
                    //column_set、coordinate_system_type、geo_json_size、geo_json_url
                    const {
                        file: {
                            response: {
                                data: {
                                    source_id,
                                    geo_json_url,
                                }
                            }
                        }
                    } = e;
                    console.log("fileUrl--->", geo_json_url, fileName);
                    formData.geoJSON = geo_json_url;
                    formData.sourceId = source_id;
                    formData.name = fileName;
                    form.setFieldValue('name', fileName)
                    setFormData({ ...formData });
                }
            }
        } catch (e) {
            console.log("出错了--->", e)
        }
    }

    const beforeUploadShpFile = (file: any) => {
        console.log("beforeUploadShpFile--->", file)
        if (file.size > 10 * 1024 * 1024) {
            toastShort('error', '上传文件不得大于10M')
            return false;
        }
    }


    const queryMapTopic = () => {
        let params = {
            size: 9999,
            page: 1,
            params: {
                layerType: 'topic'
            }
        }
        if (pageParamsTag == 'pageIndex') {
            //@ts-ignore
            params.pageNum = 1;
            //@ts-ignore
            params.pageSize = 9999
        }
        if (!isEmpty(defaultMapLayerPid)) {
            //@ts-ignore
            params.pid = defaultMapLayerPid;
        }
        queryMapLayerPromiseFunc && queryMapLayerPromiseFunc(params)
            .then(res => {
                console.log("queryMapLayerPromiseFunc---->", res)
                const tempMapTopicSelectOptions = [];
                res.data.list.forEach(ele => {
                    let option = {
                        label: ele.name,
                        value: ele.id
                    }
                    tempMapTopicSelectOptions.push(option);

                })
                setMapTopicSelectOptions(tempMapTopicSelectOptions)
            })
            .catch(err => {
                console.log("queryMapLayerPromiseFunc---->err", err)
            })
    }

    const onNameTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        handleSetFormData('name', getChangeEventValue(e));
    }

    return (
        <Modal
            title={'导入地理图层'}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={612}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div className='custom-modal-container'>
                <Form
                    size={'middle'}
                    form={form}
                    layout={'horizontal'}
                    autoComplete="off"
                    labelAlign={'right'}
                    labelCol={{ span: 4 }}
                    style={{ width: '100%' }}
                >
                    <Form.Item
                        label="shp文件"
                        name={'shpFile'}
                        rules={[{ required: formData.id ? false : true, message: '请输入专题名称' }]}
                    >
                        <Dragger
                            {...props}
                            style={{ width: '426px' }}
                            onChange={onFileChange}
                            maxCount={1}
                            beforeUpload={beforeUploadShpFile}
                            action={uploadActionUrl}
                            accept=".zip"
                            disabled={!isEmpty(formData.id)}
                        >
                            <p
                                className="ant-upload-drag-icon"
                                style={{ marginTop: 32 }}
                            >
                                <FileZipOutlined />
                            </p>
                            <p className="ant-upload-text">
                                {shpFileName ? shpFileName : '点击或拖入Shp压缩包文件'}
                                {/* {uploadProgress ? uploadProgress.toFixed(2) + '%' : null} */}
                            </p>
                            <p
                                className="ant-upload-hint"
                                style={{ marginBottom: 32 }}
                            >
                                150M之内的APK文件，注意需保持签名一致
                            </p>
                        </Dragger>
                    </Form.Item>
                    <Form.Item
                        label="所属专题"
                        name={'pid'}
                        rules={[{ required: true, message: '请输入专题名称' }]}
                    >
                        <Select
                            placeholder='请选择所属地理专题'
                            style={{ width: '426px' }}
                            maxLength={20}
                            value={formData.pid}
                            onChange={onMapTopicIdChange}
                            options={mapTopicSelectOptions}
                            loading={mapToicLoading}
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item
                        label="图层名称"
                        name={'name'}
                        rules={[{ required: true, message: '请输入地理图层名称' }]}
                    >
                        <Input
                            placeholder='请输入地理图层名称（默认为文件名）'
                            style={{ width: '426px' }}
                            maxLength={20}
                            value={formData.name}
                            onChange={onNameTextChange}
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item
                        label="类型"
                        name={'layerType'}
                        rules={[{ required: true, message: '请选择图层类型' }]}
                    >
                        <Select
                            placeholder='请选择图层类型'
                            style={{ width: '426px' }}
                            maxLength={20}
                            value={formData.layerType}
                            onChange={onLayerTypeChange}
                            options={[
                                {
                                    value: 'shape',
                                    label: '面'
                                },
                                {
                                    value: 'line',
                                    label: '线'
                                },
                                {
                                    value: 'symbol',
                                    label: '点'
                                }
                            ]}
                            allowClear
                        />
                    </Form.Item>

                </Form>
            </div>
        </Modal>
    )
}


export default forwardRef(UploadShpFileModal);